/******************************************************/
/* Goblin's Cube - Rubik's cube game for Wii Homebrew */
/* Copyright (C) 2009 Ricardo Bueno Cordeiro          */
/* Licensed under de GNU General Public License v2.0  */
/*   See license_gplv2.txt for detalis                */
/******************************************************/

#include <gccore.h>
#include <ogc/lwp_watchdog.h>
#include <wiiuse/wpad.h>

#include "control.h"
#include "draw.h"
#include "random.h"

#include "sound.h"
#include "sound_ogg_loader.h"

#include "drop1_ogg.h"
#include "drop2_ogg.h"
#include "drop3_ogg.h"
#include "drop4_ogg.h"
#include "drop5_ogg.h"
#include "drop6_ogg.h"
#include "drop7_ogg.h"

Control::Control() {
	this->last_cube_solved_state = Cube::cube.is_solved();
	this->solved_time = 0;

	// Load sounds
	this->drop_sound[0].load(new SoundOggLoader(drop1_ogg, drop1_ogg_size));
	this->drop_sound[1].load(new SoundOggLoader(drop2_ogg, drop2_ogg_size));
	this->drop_sound[2].load(new SoundOggLoader(drop3_ogg, drop3_ogg_size));
	this->drop_sound[3].load(new SoundOggLoader(drop4_ogg, drop4_ogg_size));
	this->drop_sound[4].load(new SoundOggLoader(drop5_ogg, drop5_ogg_size));
	this->drop_sound[5].load(new SoundOggLoader(drop6_ogg, drop6_ogg_size));
	this->drop_sound[6].load(new SoundOggLoader(drop7_ogg, drop7_ogg_size));
	this->random_sound_frame = 0;
}

int Control::update(WPADData *wiimote_data, int state) {
	if (wiimote_data->btns_d & WPAD_BUTTON_HOME)
		return 1;

	if (!this->last_cube_solved_state && Cube::cube.is_solved()) {
		this->highscore.just_solved();
		this->solved_time = gettime() + (TB_TIMER_CLOCK * 100);
		WPAD_Rumble(WPAD_CHAN_0, 1);
	}
	this->last_cube_solved_state = Cube::cube.is_solved();
	
	if (this->solved_time < gettime())
		WPAD_Rumble(WPAD_CHAN_0, 0);

	if (!Cube::cube.is_solved()) {
		this->highscore.update(wiimote_data, CONTROL_HIDDEN);
		this->game.update(wiimote_data, CONTROL_FOREGROUND);
	} else {
		this->game.update(wiimote_data, CONTROL_BACKGROUND);
		this->highscore.update(wiimote_data, CONTROL_FOREGROUND);
	}

	if (!(generate() % 10)) {
		this->random_sound_frame += generate() % 20;
		if (this->random_sound_frame > 600) {
			this->drop_sound[generate() % 7].play(0, 255, 255);
			this->random_sound_frame = 0;
		}
	}

	return 0;
}

void Control::draw(int state) {
	if (!Cube::cube.is_solved()) {
		this->highscore.draw(CONTROL_HIDDEN);
		this->game.draw(CONTROL_FOREGROUND);
	} else {
		this->game.draw(CONTROL_BACKGROUND);
		this->highscore.draw(CONTROL_FOREGROUND);
	}
}

void Control::text(int state) {
	if (!Cube::cube.is_solved()) {
		this->highscore.text(CONTROL_HIDDEN);
		this->game.text(CONTROL_FOREGROUND);
	} else {
		this->game.text(CONTROL_BACKGROUND);
		this->highscore.text(CONTROL_FOREGROUND);
	}
}
